<template>
  <div class="tourism-products app-container">
    <!-- 搜索表单 -->
    <el-card class="search-card filter-container">
      <div class="filter-header">
        <div classclass="filter-title">搜索条件</div>
        <div class="filter-actions">
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </div>
      </div>
      
      <common-form
        ref="searchFormRef"
        v-model="searchFormData"
        :form-fields="searchFormFields"
        label-width="80px"
        :gutter="20"
        class="filter-form"
      />
    </el-card>
    
    <!-- 表格操作栏 -->
    <el-card class="table-card">
      <template #header>
        <div class="table-header">
          <div class="table-title">旅游商品列表</div>
          <div class="table-actions">
            <el-button type="primary" @click="handleAdd">新增商品</el-button>
            <el-button type="danger" :disabled="selectedRows.length === 0" @click="handleBatchDelete">
              批量删除
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 商品列表表格 -->
      <common-table
        :table-data="tableData"
        :table-columns="tableColumns"
        show-selection
        show-index
        :show-pagination="true"
        :pagination="pagination"
        @selection-change="handleSelectionChange"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
        <template #status="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'info'">
            {{ row.status === 1 ? '上架' : '下架' }}
          </el-tag>
        </template>
        
        <template #price="{ row }">
          ¥{{ row.price }}
        </template>
        
        <template #actions="{ row }">
          <el-button size="small" type="primary" link @click="handleEdit(row)">编辑</el-button>
          <el-button size="small" type="danger" link @click="handleDelete(row)">删除</el-button>
        </template>
      </common-table>
    </el-card>
    
    <!-- 商品编辑/新增弹窗 -->
    <common-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      :confirm-loading="dialogLoading"
      @confirm="handleDialogConfirm"
      @cancel="handleDialogCancel"
      width="600px"
    >
      <common-form
        ref="productFormRef"
        v-model="productFormData"
        :form-fields="productFormFields"
        :rules="productFormRules"
        label-width="100px"
      />
    </common-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import CommonForm from '@/components/CommonForm.vue'
import CommonTable from '@/components/CommonTable.vue'
import CommonDialog from '@/components/CommonDialog.vue'
import { validateRules } from '@/utils/rules'
import dayjs from 'dayjs'

// 搜索表单引用
const searchFormRef = ref()

// 搜索表单数据
const searchFormData = reactive({
  name: '',
  status: ''
})

// 搜索表单字段配置
const searchFormFields = [
  {
    prop: 'name',
    label: '商品名称',
    type: 'input',
    col: { xs: 24, sm: 12, md: 8 }
  },
  {
    prop: 'status',
    label: '状态',
    type: 'select',
    options: [
      { label: '全部', value: '' },
      { label: '上架', value: 1 },
      { label: '下架', value: 0 }
    ],
    col: { xs: 24, sm: 12, md: 8 }
  }
]

// 表格数据
const tableData = ref([
  {
    id: 1,
    name: '三亚五日游',
    description: '海南三亚五日游套餐，包含机票酒店',
    price: 2999,
    status: 1,
    createTime: dayjs().format('YYYY-MM-DD HH:mm:ss')
  },
  {
    id: 2,
    name: '北京三日游',
    description: '北京经典景点三日游',
    price: 1888,
    status: 1,
    createTime: dayjs().subtract(1, 'day').format('YYYY-MM-DD HH:mm:ss')
  },
  {
    id: 3,
    name: '云南大理丽江双飞六日游',
    description: '大理丽江双飞六日游，体验古城风情',
    price: 3299,
    status: 0,
    createTime: dayjs().subtract(2, 'day').format('YYYY-MM-DD HH:mm:ss')
  }
])

// 表格列配置
const tableColumns = [
  {
    prop: 'name',
    label: '商品名称',
    minWidth: 150
  },
  {
    prop: 'description',
    label: '商品描述',
    minWidth: 200
  },
  {
    prop: 'price',
    label: '价格',
    width: 100,
    render: 'price'
  },
  {
    prop: 'status',
    label: '状态',
    width: 80,
    render: 'status'
  },
  {
    prop: 'createTime',
    label: '创建时间',
    width: 180,
    formatter: (value) => {
      return value ? dayjs(value).format('YYYY-MM-DD HH:mm:ss') : ''
    }
  }
]

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 3,
  pageSizes: [10, 20, 50]
})

// 已选中的行
const selectedRows = ref([])

// 弹窗相关
const dialogVisible = ref(false)
const dialogLoading = ref(false)
const dialogType = ref('add') // add 或 edit

// 用户表单引用
const productFormRef = ref()

// 用户表单数据
const productFormData = reactive({
  id: undefined,
  name: '',
  description: '',
  price: undefined,
  status: 1
})

// 用户表单字段配置
const productFormFields = [
  {
    prop: 'name',
    label: '商品名称',
    type: 'input',
    attrs: { placeholder: '请输入商品名称' }
  },
  {
    prop: 'description',
    label: '商品描述',
    type: 'textarea',
    attrs: { placeholder: '请输入商品描述', rows: 3 }
  },
  {
    prop: 'price',
    label: '价格',
    type: 'number',
    attrs: { placeholder: '请输入价格', min: 0, controlsPosition: 'right' }
  },
  {
    prop: 'status',
    label: '状态',
    type: 'switch',
    attrs: { activeValue: 1, inactiveValue: 0, activeText: '上架', inactiveText: '下架' }
  }
]

// 用户表单验证规则
const productFormRules = {
  name: [
    validateRules.required('请输入商品名称'),
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  price: [
    validateRules.required('请输入价格'),
    { type: 'number', min: 0, message: '价格必须大于等于0', trigger: 'blur' }
  ]
}

// 计算属性 - 弹窗标题
const dialogTitle = computed(() => {
  return dialogType.value === 'add' ? '新增商品' : '编辑商品'
})

// 搜索事件
const handleSearch = () => {
  ElMessage.success('执行搜索操作')
  // 实际开发中这里会发送请求获取数据
}

// 重置搜索条件
const handleReset = () => {
  searchFormRef.value.resetFields()
}

// 添加商品
const handleAdd = () => {
  dialogType.value = 'add'
  // 重置表单数据
  Object.keys(productFormData).forEach(key => {
    productFormData[key] = key === 'status' ? 1 : ''
  })
  dialogVisible.value = true
}

// 编辑商品
const handleEdit = (row) => {
  dialogType.value = 'edit'
  // 填充表单数据
  Object.keys(productFormData).forEach(key => {
    productFormData[key] = row[key]
  })
  dialogVisible.value = true
}

// 删除商品
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除商品 "${row.name}" 吗？`, '提示', {
    type: 'warning'
  }).then(() => {
    // 实际开发中这里会发送删除请求
    ElMessage.success('删除成功')
  }).catch(() => {
    // 用户取消删除
  })
}

// 批量删除
const handleBatchDelete = () => {
  ElMessageBox.confirm(`确认删除选中的 ${selectedRows.value.length} 个商品吗？`, '提示', {
    type: 'warning'
  }).then(() => {
    // 实际开发中这里会发送批量删除请求
    ElMessage.success('批量删除成功')
  }).catch(() => {
    // 用户取消删除
  })
}

// 弹窗确认
const handleDialogConfirm = async () => {
  try {
    await productFormRef.value.validate()
    dialogLoading.value = true
    
    // 模拟异步提交
    setTimeout(() => {
      dialogLoading.value = false
      dialogVisible.value = false
      ElMessage.success(dialogType.value === 'add' ? '新增成功' : '编辑成功')
      // 实际开发中这里会发送保存请求并刷新数据
    }, 1000)
  } catch (error) {
    // 验证失败
  }
}

// 弹窗取消
const handleDialogCancel = () => {
  productFormRef.value.resetFields()
}

// 表格选择事件
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 分页大小改变
const handleSizeChange = (val) => {
  pagination.pageSize = val
  // 实际开发中这里会重新获取数据
  ElMessage.info(`每页显示 ${val} 条`)
}

// 当前页改变
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  // 实际开发中这里会重新获取数据
  ElMessage.info(`当前第 ${val} 页`)
}
</script>

<style scoped>
.tourism-products {
  padding: 20px;
}

.app-container {
  background-color: #fff;
  padding: 20px;
}

.filter-container {
  margin-bottom: 20px;
}

.filter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.filter-title {
  font-weight: bold;
  font-size: 16px;
  color: #333;
}

.filter-actions {
  display: flex;
  gap: 10px;
}

.table-card {
  margin-top: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-title {
  font-weight: bold;
  font-size: 16px;
  color: #333;
}

.table-actions {
  display: flex;
  gap: 10px;
}

:deep(.el-card__header) {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
  background-color: #fafafa;
}
</style>